package com.one.blocks.rbac.controller;

import com.one.blocks.mvc.exception.BusinessException;
import com.one.blocks.mvc.response.ResponseHelper;
import com.one.blocks.mvc.response.WebResponse;
import com.one.blocks.rbac.enums.RbacResponseEnum;
import com.one.blocks.security.exception.AuthcException;
import com.one.blocks.security.exception.AuthzException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;

import static com.one.blocks.rbac.constant.RbacConstant.REQUEST_ERROR_KEY;


/**
 * @author linfuxin Created on 2022-06-10 09:13:05
 */
@ApiIgnore
@RequestMapping({"${app.error.biz-path:${error.biz-path:/biz/error}}"})
@RestController
@Slf4j
public class BizExceptionController {

    @GetMapping
    public WebResponse<Void> restFilterError(ServletRequest request) {
        RuntimeException exception = (RuntimeException) request.getAttribute(REQUEST_ERROR_KEY);
        if (exception instanceof AuthcException) {
            return ResponseHelper.fail(((AuthcException) exception).getCode(), ((AuthcException) exception).getMsg());
        }
        if (exception instanceof AuthzException) {
            return ResponseHelper.fail(((AuthzException) exception).getCode(), ((AuthzException) exception).getMsg());
        }
        if (exception instanceof BusinessException) {
            return ResponseHelper.fail((BusinessException) exception);
        }
        log.error("filter error!{}", exception.getMessage());
        return ResponseHelper.fail(RbacResponseEnum.UNKNOWN_ERROR);
    }
}
